#pragma once

#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#include"unistd.h"
#include"log.hpp"

#define NUM 1024

namespace client
{

    using namespace std;

    class TcpClient
    {
    public:
        TcpClient(const string& serverip,const uint16_t& serverport)
        :_sock(-1),_serverip(serverip),_serverport(serverport)
        {}
        void initClient()
        {
            // 1.创建socket
            _sock = socket(AF_INET,SOCK_STREAM,0);
            if(_sock < 0)
            {
                cout << "sock create error" << endl;
                exit(2);
            }
            
            // 2.tcp要不要bin？要！不需要显示bind，让OS随机指定port！
            // 3.要不要listen？不要
            // 4.要不要accept？不要
            // 5.要什么呢？要发起链接
        }
        void start()
        {
            struct sockaddr_in server;
            memset(&server,0,sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            if(connect(_sock,(struct sockaddr*)&server,sizeof(server)) != 0)
            {
                cerr << "socket connect error" << endl;
            }
            else
            {
                string msg;
                while(true)
                {
                    cout << "Enter# ";
                    getline(cin,msg);
                    write(_sock,msg.c_str(),msg.size());

                    char buffer[NUM];
                    int n = read(_sock,buffer,sizeof(buffer)-1);
                    if(n > 0)
                    {
                        // 目前把读到的数据当成字符串，截至目前
                        buffer[n] = 0;
                        cout << "Server回显# " << buffer << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~TcpClient()
        {
            if(_sock >= 0) close(_sock);
        }
    private:
        int _sock;
        string _serverip;
        uint16_t _serverport;
    };
}